#include "AIP650.h"
#include "bsp_port.h"

void AIP650_WriteCmd(uint8_t Reg, uint8_t cmd);

void AIP650_Init(void)
{
    LL_mDelay(100);
    AIP650_WriteCmd(0x48, 0x01);
}

void AIP_Start(void)
{
    KEY_SCL_1;
    KEY_SDA_1;
    bsp_Delay_us(20);
    KEY_SDA_0;
}

void AIP_Stop(void)
{
    KEY_SCL_1;
    KEY_SDA_0;
    bsp_Delay_us(50);
    KEY_SDA_1;
}

void AIP_SendByte(uint8_t data)
{
    uint16_t Timeout = 0x1ff;

    KEY_SCL_0;
    bsp_Delay_us(10);
    for (uint8_t i = 0; i < 8; i++)
    {

        KEY_SCL_0;
        if (data & 0x80)
        {
            KEY_SDA_1;
        }
        else
        {
            KEY_SDA_0;
        }

        bsp_Delay_us(20);
        KEY_SCL_1;
        bsp_Delay_us(20);
        data <<= 1;
    }

    KEY_SCL_0;
    bsp_Delay_us(20);
    KEY_SDA_INT;
    KEY_SCL_1;
    while (KEY_SDA_ISIN && Timeout--)
    {
        bsp_Delay_us(2);
    };
    bsp_Delay_us(20);

    KEY_SCL_0;
    KEY_SDA_OUT;
    bsp_Delay_us(20);
}

uint8_t AIP_ReadByte(void)
{
    uint16_t Timeout = 0x1ff;
    uint8_t Tmp = 0;
    KEY_SCL_0;
    bsp_Delay_us(20);
    KEY_SDA_INT;
    bsp_Delay_us(20);

    for (uint8_t i = 0; i < 8; i++)
    {
        Tmp <<= 1;
        KEY_SCL_0;
        bsp_Delay_us(20);
        KEY_SCL_1;
        bsp_Delay_us(20);
        if (KEY_SDA_ISIN)
        {
            Tmp |= 1;
        }
        else
        {
            Tmp |= 0;
        }
    }

    KEY_SCL_0;
    bsp_Delay_us(20);
    KEY_SCL_1;
    while (KEY_SDA_ISIN && Timeout--)
        ;
    KEY_SCL_0;
    KEY_SDA_OUT;
    bsp_Delay_us(20);
    return Tmp;
}

void AIP650_ReadKey(uint8_t Reg, uint8_t *data)
{
    AIP_Start();
    AIP_SendByte(Reg);
    *data = AIP_ReadByte();
    AIP_Stop();
}

void AIP650_WriteCmd(uint8_t Reg, uint8_t cmd)
{
    AIP_Start();
    AIP_SendByte(Reg);
    AIP_SendByte(cmd);
    AIP_Stop();
}

uint32_t AIP_GetKeyValue(void)
{
    uint8_t Key = 0;
    uint32_t KeyValue = 0;
    AIP650_ReadKey(0x4F, &Key);
    if (Key & 0x40)
    {
        KeyValue = ((Key >> 3) & 0x07) + 1;
        KeyValue += (Key & 0x03) * 5;
    }

    return (KeyValue);
}
